import { Extension } from '@tiptap/react';
import '@tiptap/extension-text-style';

export const UnderlineExtension = Extension.create({
  name: 'underline',
  addOptions() {
    return {
      types: ['textStyle'],
    };
  },
  addGlobalAttributes() {
    return [
      {
        types: this.options.types,
        attributes: {
          textDecoration: {
            default: null,
            parseHTML: (element) => element.style.textDecoration,
            renderHTML: (attributes) => {
              if (!attributes.textDecoration) {
                return {};
              }
              return {
                style: `text-decoration: ${attributes.textDecoration}`,
              };
            },
          },
        },
      },
    ];
  },
  addCommands() {
    return {
      toggleUnderline:
        () =>
        ({ chain, editor }) => {
          const hasUndeline = !!editor.getAttributes('textStyle').textDecoration;
          return chain()
            .setMark('textStyle', { textDecoration: hasUndeline ? null : 'underline' })
            .run();
        },
      setUnderline:
        () =>
        ({ chain }) => {
          return chain().setMark('textStyle', { textDecoration: 'underline' }).run();
        },
      unsetUnderline:
        () =>
        ({ chain }) => {
          return chain()
            .setMark('textStyle', { textDecoration: null })
            .removeEmptyTextStyle()
            .run();
        },
    };
  },
});
